#include "ThreadPool.h"
#include <unistd.h>

using namespace tp;

ThreadPool::ThreadPool(size_t queSize, size_t threadNum)
    :_queSize(queSize)
     ,_threadNum(threadNum)
     ,_que(queSize)
     ,_isExit(false)
{}

ThreadPool::~ThreadPool()
{
}

void ThreadPool::start()
{
    for (size_t i = 0; i < _threadNum; ++i)
    {
        std::shared_ptr<Thread> thread(new Thread(std::bind(&ThreadPool::doTask, std::ref(*this))));
        _threads.push_back(thread);
    }

    for (auto& it : _threads)
    {
        it->start();
    }
}

void ThreadPool::stop()
{
    if (!_isExit)
    {
        while(!_que.empty())
        {
            ::sleep(2);
        }
        _isExit = true;
        _que.wakeup();

        for (auto& it : _threads)
        {
            it->join();
        }
    }
}

void ThreadPool::addTask(const Func& func)
{
    _que.push(func);
}

void ThreadPool::doTask()
{
    while (!_isExit)
    {
        Func func = _que.pop();
        if (func)
        {
            func();
        }
    }
}
